import React from 'react';
import { Modal, Form, Input } from 'antd';

interface TextInputModalProps {
  open: boolean;
  loading?: boolean;
  onOk: (value: string) => void;
  onCancel: () => void;
  title?: string;
  label?: string;
  placeholder?: string;
  okText?: string;
  cancelText?: string;
  validateMessage?: string;
  initialValue?: string;
}

const TextInputModal: React.FC<TextInputModalProps> = ({
  open,
  loading = false,
  onOk,
  onCancel,
  title = '请输入',
  label = '名称',
  placeholder = '请输入',
  okText = '确认',
  cancelText = '取消',
  validateMessage = '请输入内容',
  initialValue = '',
}) => {
  const [form] = Form.useForm();

  React.useEffect(() => {
    if (open) {
      form.setFieldsValue({ value: initialValue });
    } else {
      form.resetFields();
    }
  }, [open, initialValue, form]);

  const handleOk = async () => {
    try {
      const { value } = await form.validateFields();
      onOk(value);
      form.resetFields();
    } catch (e) {
      // 校验失败
    }
  };

  const handleCancel = () => {
    onCancel();
    form.resetFields();
  };

  return (
    <Modal
      open={open}
      title={title}
      onOk={handleOk}
      onCancel={handleCancel}
      confirmLoading={loading}
      okText={okText}
      cancelText={cancelText}
      maskClosable={false}
    >
      <Form
        form={form}
        layout='vertical'
        name='text_input_modal_form'
        initialValues={{ value: initialValue }}
      >
        <Form.Item
          name='value'
          label={label}
          rules={[{ required: true, message: validateMessage }]}
        >
          <Input
            placeholder={placeholder}
            onPressEnter={handleOk}
            autoFocus
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default TextInputModal;
